package cn.eng.org.controller;


import cn.eng.basic.utils.AjaxResult;
import cn.eng.basic.utils.PageList;
import cn.eng.org.domain.Department;
import cn.eng.org.query.DepartmentQuery;
import cn.eng.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestControllerAdvice
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询单个对象
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department loadById(@PathVariable("id") Long id) {
        return departmentService.loadById(id);
    }

    /**
     * 查询所有对象
     *
     * @return
     */
    @GetMapping()
    public List<Department> loadAll() {
        return departmentService.loadAll();
    }

    /**
     * 添加和修改
     *
     * @param department
     * @return
     */
    @PutMapping()
    public AjaxResult saveOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() != null) {
                departmentService.update(department);
            } else {
                departmentService.save(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setSuccess(false).setMsg("系统繁忙， 请稍后再试");
        }
    }

    /**
     * 删除单个对象
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id) {
        try {
            departmentService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setSuccess(false).setMsg("系统繁忙，请稍后再试");
        }
    }

    /**
     * 分页查询
     * @param departmentQuery
     * @return
     */
    @PostMapping()
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery) {
        return departmentService.queryPage(departmentQuery);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping()
    public AjaxResult patchDel(@RequestBody Long[] ids) {
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setSuccess(false).setMsg("操作失败");
        }
    }

    /**
     * 部门级联树
     *
     * @return
     */
    @GetMapping("/deptTree")
    public List<Department> deptTree() {
        return departmentService.deptTree();
    }

}
